package client;

import java.io.*;
import java.net.Socket;

public class OutputConsole {

    private static final int defaultPort = 9999;
    private static final String localhost = "127.0.0.1";
    private BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    private static OutputConsole output = new OutputConsole();

    private int port;
    private Socket sock;

    public static void main(String... args) {
        output.getArguments(args);
        output.connectWithInputConsole();
        output.ShowInformationFromInputConsole();
    }

    private void getArguments(String... args) {
        if (args.length != 1) {
            this.setDefaultPort();
        } else {
            try {
                this.port = Integer.parseUnsignedInt(args[0]);
            } catch (NumberFormatException e) {
                this.setDefaultPort();
            }
        }
    }

    private void ShowInformationFromInputConsole() {
        try {
            DataInputStream in = new DataInputStream(this.sock.getInputStream());
            while (true) {

                System.out.println(in.readUTF());
            }
        } catch (IOException e) {
            System.out.println("Input console was closed!");
            System.out.println("Exit");
            System.exit(1);
        }
    }

    private Socket connectWithInputConsole() {
        Socket sock = null;
        RECONNECT:
        while (true) {
            try {

                System.out.println("Waiting for input console...");
                sock = new Socket(localhost, port);
                System.out.println("Connected for input console.");
                this.sock = sock;
                return sock;
            } catch (IOException e) {

                System.out.println("Can't connect with input console due:");
                System.out.println(e.toString());
                boolean flag = true;
                while (flag) {
                    System.out.println("Exit(\"e\") or try to reconnect(\"r\")?");
                    String input = "e";
                    try {
                        input = reader.readLine();
                    } catch (IOException ignored) {
                    }
                    switch (input) {
                        case ("e"):
                            System.out.println("Exit");
                            System.exit(0);
                            break;
                        case ("r"):
                            flag = false;
                            break;
                        default:
                    }
                }
            }
        }
    }

    private void setDefaultPort() {
        System.out.println("Warning: port number not set, using " + defaultPort + " for internal communication");
        this.port = defaultPort;
    }
}
